package com.dp.appi.util;

import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.FileSet;

import java.io.*;

/**
 * Created by Administrator on 2016/8/22.
 */
public class ZipHandle {
    private static File zipFile;

    /**
     * 构造函数
     * @param zipPath 最终压缩生成的压缩文件：目录+压缩文件名.zip
     */
    public ZipHandle(String zipPath) {
        zipFile = new File(zipPath);
    }

    /**
     * 执行压缩操作
     *
     * @param filePath 需要被压缩的文件/文件夹
     */
    public  int compressor(String filePath) {
        File srcdir = new File(filePath);
        if (!srcdir.exists() && !srcdir.isDirectory()) {
            throw new RuntimeException(filePath + "文件夹不存在！");
        }
        Project prj = new Project();
        Zip zip = new Zip();
//        zip.setEncoding("UTF-8");
        zip.setProject(prj);
        zip.setDestFile(zipFile);
        FileSet fileSet = new FileSet();
        fileSet.setProject(prj);
        fileSet.setDir(srcdir);
        //fileSet.setIncludes("**/*.java"); //包括哪些文件或文件夹 eg:zip.setIncludes("*.java");
        //fileSet.setExcludes(...); //排除哪些文件或文件夹
        zip.addFileset(fileSet);
        zip.execute();
        System.out.println("打包完成");
        return 1;
    }



    public static ByteArrayOutputStream outFile(String zipPath){
        //读取压缩包
        File filezip = new File(zipPath);
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            FileInputStream inStream = new FileInputStream(filezip);
            BufferedInputStream bis = new BufferedInputStream(inStream);

            int c = bis.read();
            while (c != -1) {
                baos.write(c);
                c = bis.read();
            }
            bis.close();
            inStream.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return baos;
    }

    public static void main(String[] args) {
        ZipHandle zh = new ZipHandle("G:\\ProjectStage_4247"+".zip");
        zh.compressor("G:\\ProjectStage_4247");
        ByteArrayOutputStream b = zh.outFile("G:\\ProjectStage_4247" + ".zip");

        byte[] k = b.toByteArray();
        String sendString = null;
        try {
            sendString = new String(k,"ISO-8859-1" );
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.print(sendString);

    }
}
